package com.livi.security.config.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.livi.security.model.commom.BaseResponse;
import com.livi.security.model.commom.ResultCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 匿名用户访问无权限资源时的异常
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			AuthenticationException e) throws IOException, ServletException {
		String res = JSONObject.toJSONString(new BaseResponse<>(false, ResultCode.AUTH_FAIL));
		httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);// 401，未登录
		httpServletResponse.setContentType("text/json;charset=utf-8");
		httpServletResponse.getWriter().write(res);
	}
}
